#!/bin/bash

echo "=========================================="
echo "  分布式事务回滚测试"
echo "=========================================="
echo ""

# 记录初始状态
echo "【1】记录初始状态"
echo "库存 product_id=1:"
docker exec springcloud-mysql mysql -uroot -proot123456 seata_storage \
  -e "SELECT product_id, used, residue FROM tb_storage WHERE product_id=1;" 2>/dev/null | tail -n +2

echo "账户 user_id=1:"
docker exec springcloud-mysql mysql -uroot -proot123456 seata_account \
  -e "SELECT user_id, used, residue FROM tb_account WHERE user_id=1;" 2>/dev/null | tail -n +2

echo "订单总数:"
BEFORE_COUNT=$(docker exec springcloud-mysql mysql -uroot -proot123456 seata_order \
  -e "SELECT COUNT(*) as count FROM tb_order;" 2>/dev/null | tail -n +2)
echo "$BEFORE_COUNT"

echo ""
echo "【2】测试库存不足场景（购买1000个，但只有998个库存）"
RESULT=$(curl -s -X POST http://localhost:8001/order/create/at \
  -H "Content-Type: application/json" \
  -d '{"userId":1,"productId":1,"count":1000,"money":10000.00}')

echo "API 返回: $RESULT"
echo ""

sleep 3

echo "【3】验证数据是否回滚"
echo "库存 product_id=1（应该未变化）:"
docker exec springcloud-mysql mysql -uroot -proot123456 seata_storage \
  -e "SELECT product_id, used, residue FROM tb_storage WHERE product_id=1;" 2>/dev/null | tail -n +2

echo "账户 user_id=1（应该未变化）:"
docker exec springcloud-mysql mysql -uroot -proot123456 seata_account \
  -e "SELECT user_id, used, residue FROM tb_account WHERE user_id=1;" 2>/dev/null | tail -n +2

echo "订单总数（应该未增加）:"
AFTER_COUNT=$(docker exec springcloud-mysql mysql -uroot -proot123456 seata_order \
  -e "SELECT COUNT(*) as count FROM tb_order;" 2>/dev/null | tail -n +2)
echo "$AFTER_COUNT"

echo ""
echo "【结论】"
if echo "$RESULT" | grep -q '"code":500'; then
    echo "✅ API 正确返回失败"
    if [ "$BEFORE_COUNT" == "$AFTER_COUNT" ]; then
        echo "✅ 订单数量未增加"
        echo "✅ 回滚测试成功！"
    else
        echo "❌ 订单数量发生变化，回滚失败！"
    fi
else
    echo "❌ API 没有返回失败，这是一个BUG！"
fi

echo ""
echo "=========================================="
echo "  ✅ 回滚测试完成！"
echo "=========================================="
echo ""
echo "说明："
echo "  - 库存不足导致 SQL 执行失败"
echo "  - 分布式事务自动回滚"
echo "  - 数据保持一致性"
echo ""
echo "下一步："
echo "  - 运行 undo_log 测试：./resources/scripts/07-undo_log测试.sh"
echo "  - 查看 Seata 日志：docker logs -f springcloud-seata"
